'use client'

import { useState, useEffect } from 'react'
import { useSession } from 'next-auth/react'
import { Button } from '@/components/ui/button'
import { 
  Card, 
  CardContent, 
  CardDescription, 
  CardFooter, 
  CardHeader, 
  CardTitle 
} from '@/components/ui/card'
import { 
  Dialog, 
  DialogContent, 
  DialogDescription, 
  DialogFooter, 
  DialogHeader, 
  DialogTitle, 
  DialogTrigger 
} from '@/components/ui/dialog'
import { 
  Table, 
  TableBody, 
  TableCell, 
  TableHead, 
  TableHeader, 
  TableRow 
} from '@/components/ui/table'
import { 
  DropdownMenu, 
  DropdownMenuContent, 
  DropdownMenuItem, 
  DropdownMenuLabel, 
  DropdownMenuSeparator, 
  DropdownMenuTrigger 
} from '@/components/ui/dropdown-menu'
import { 
  Tabs, 
  TabsContent, 
  TabsList, 
  TabsTrigger 
} from '@/components/ui/tabs'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { Skeleton } from '@/components/ui/skeleton'
import { toast } from '@/components/ui/use-toast'
import { CheckCircle, Copy, MoreHorizontal, Trash2, UserPlus, X } from 'lucide-react'
import { ProjectRole, RolePermissionLevel } from '@/types/team'

interface ProjectMember {
  id: string
  userId: string
  projectId: string
  role: ProjectRole
  joinedAt: string
  user: {
    id: string
    name: string | null
    email: string | null
    image: string | null
  }
}

interface ProjectInvite {
  id: string
  email: string
  projectId: string
  role: ProjectRole
  status: 'PENDING' | 'ACCEPTED' | 'DECLINED'
  token: string
  createdAt: string
  expires: string
  inviter: {
    id: string
    name: string | null
    image: string | null
  }
  message?: string
}

interface TeamManagementProps {
  projectId: string
}

export default function TeamManagement({ projectId }: TeamManagementProps) {
  const { data: session, status } = useSession()
  const [members, setMembers] = useState<ProjectMember[]>([])
  const [invites, setInvites] = useState<ProjectInvite[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [isError, setIsError] = useState(false)
  const [userRole, setUserRole] = useState<ProjectRole | null>(null)
  const [isInviteModalOpen, setIsInviteModalOpen] = useState(false)
  const [isSending, setIsSending] = useState(false)
  const [email, setEmail] = useState('')
  const [role, setRole] = useState<ProjectRole>(ProjectRole.MEMBER)
  const [message, setMessage] = useState('')
  const [copiedInvite, setCopiedInvite] = useState<string | null>(null)
  const [activeTab, setActiveTab] = useState('members')
  
  // 获取团队成员列表
  const fetchMembers = async () => {
    try {
      const res = await fetch(`/api/project/members?projectId=${projectId}`)
      const data = await res.json()
      
      if (data.success) {
        setMembers(data.data)
        // 设置当前用户的角色
        const currentUserMember = data.data.find((m: ProjectMember) => 
          m.userId === session?.user?.id
        )
        if (currentUserMember) {
          setUserRole(currentUserMember.role)
        }
      } else {
        setIsError(true)
        toast({
          title: "获取成员列表失败",
          description: data.message,
          variant: "destructive",
        })
      }
    } catch (error) {
      setIsError(true)
      toast({
        title: "获取成员列表失败",
        description: "无法连接到服务器",
        variant: "destructive",
      })
    } finally {
      setIsLoading(false)
    }
  }

  // 获取邀请列表
  const fetchInvites = async () => {
    try {
      const res = await fetch(`/api/project/invite?projectId=${projectId}`)
      const data = await res.json()
      
      if (data.success) {
        setInvites(data.data)
      } else {
        toast({
          title: "获取邀请列表失败",
          description: data.message,
          variant: "destructive",
        })
      }
    } catch (error) {
      toast({
        title: "获取邀请列表失败",
        description: "无法连接到服务器",
        variant: "destructive",
      })
    }
  }

  // 发送邀请
  const sendInvite = async () => {
    if (!email.trim()) {
      toast({
        title: "无效的邮箱",
        description: "请输入有效的邮箱地址",
        variant: "destructive",
      })
      return
    }
    
    setIsSending(true)
    try {
      console.log('发送邀请请求:', {
        projectId,
        email: email.trim(),
        role,
        message: message.trim(),
      })
      
      const res = await fetch('/api/project/invite', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          projectId,
          email: email.trim(),
          role,
          message: message.trim() || undefined,
        }),
      })
      
      if (!res.ok) {
        const errorText = await res.text()
        console.error('邀请请求失败:', res.status, errorText)
        throw new Error(`请求失败: ${res.status} ${errorText}`)
      }
      
      const data = await res.json()
      
      if (data.success) {
        if (data.emailSent) {
          toast({
            title: "邀请已发送",
            description: `邀请已发送到 ${email}`,
          })
        } else {
          // 邮件发送失败，显示邀请链接
          const inviteUrl = data.data?.inviteUrl || `${window.location.origin}/project/invite/accept?token=${data.data?.token}`;
          
          toast({
            title: "邀请链接已生成",
            description: "邮件发送失败，请复制下方链接手动发送",
            action: (
              <Button 
                size="sm" 
                onClick={() => {
                  navigator.clipboard.writeText(inviteUrl);
                  toast({ title: "链接已复制" });
                }}
              >
                复制链接
              </Button>
            ),
          })
        }
        
        setEmail('')
        setRole(ProjectRole.MEMBER)
        setMessage('')
        setIsInviteModalOpen(false)
        fetchInvites() // 刷新邀请列表
      } else {
        toast({
          title: "发送邀请失败",
          description: data.message,
          variant: "destructive",
        })
      }
    } catch (error) {
      console.error('发送邀请失败:', error)
      toast({
        title: "发送邀请失败",
        description: error instanceof Error ? error.message : "无法连接到服务器",
        variant: "destructive",
      })
    } finally {
      setIsSending(false)
    }
  }

  // 更新成员角色
  const updateMemberRole = async (memberId: string, userId: string, role: ProjectRole) => {
    try {
      const res = await fetch('/api/project/members', {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          projectId,
          userId,
          role,
        }),
      })
      
      const data = await res.json()
      
      if (data.success) {
        toast({
          title: "角色已更新",
          description: "成员角色已成功更新",
        })
        fetchMembers() // 刷新成员列表
      } else {
        toast({
          title: "更新角色失败",
          description: data.message,
          variant: "destructive",
        })
      }
    } catch (error) {
      toast({
        title: "更新角色失败",
        description: "无法连接到服务器",
        variant: "destructive",
      })
    }
  }

  // 移除成员
  const removeMember = async (memberId: string) => {
    try {
      const res = await fetch(`/api/project/members?projectId=${projectId}&userId=${memberId}`, {
        method: 'DELETE',
      })
      
      const data = await res.json()
      
      if (data.success) {
        toast({
          title: "成员已移除",
          description: "成员已成功从项目中移除",
        })
        fetchMembers() // 刷新成员列表
      } else {
        toast({
          title: "移除成员失败",
          description: data.message,
          variant: "destructive",
        })
      }
    } catch (error) {
      toast({
        title: "移除成员失败",
        description: "无法连接到服务器",
        variant: "destructive",
      })
    }
  }

  // 撤销邀请
  const cancelInvite = async (inviteId: string) => {
    try {
      const res = await fetch(`/api/project/invite?id=${inviteId}`, {
        method: 'DELETE',
      })
      
      const data = await res.json()
      
      if (data.success) {
        toast({
          title: "邀请已撤销",
          description: "项目邀请已成功撤销",
        })
        fetchInvites() // 刷新邀请列表
      } else {
        toast({
          title: "撤销邀请失败",
          description: data.message,
          variant: "destructive",
        })
      }
    } catch (error) {
      toast({
        title: "撤销邀请失败",
        description: "无法连接到服务器",
        variant: "destructive",
      })
    }
  }

  // 复制邀请链接
  const copyInviteLink = (token: string) => {
    const baseUrl = window.location.origin
    const inviteUrl = `${baseUrl}/project/invite/accept?token=${token}`
    
    navigator.clipboard.writeText(inviteUrl).then(() => {
      setCopiedInvite(token)
      setTimeout(() => setCopiedInvite(null), 2000)
      
      toast({
        title: "已复制",
        description: "邀请链接已复制到剪贴板",
      })
    })
  }

  // 获取角色对应的中文名称和颜色
  const getRoleBadge = (role: ProjectRole) => {
    switch (role) {
      case ProjectRole.OWNER:
        return { label: "所有者", variant: "default" as const }
      case ProjectRole.ADMIN:
        return { label: "管理员", variant: "destructive" as const }
      case ProjectRole.MEMBER:
        return { label: "成员", variant: "secondary" as const }
      case ProjectRole.VIEWER:
        return { label: "观察者", variant: "outline" as const }
      default:
        return { label: "未知", variant: "outline" as const }
    }
  }

  // 检查当前用户是否有权限执行特定操作
  const canManageMembers = () => {
    if (!userRole) return false
    return RolePermissionLevel[userRole] >= RolePermissionLevel[ProjectRole.ADMIN]
  }

  const canManageAdmin = () => {
    if (!userRole) return false
    return userRole === ProjectRole.OWNER
  }

  // 初始化数据
  useEffect(() => {
    if (status === 'authenticated' && projectId) {
      fetchMembers()
      fetchInvites()
    }
  }, [projectId, status])

  // 处理标签页切换
  const handleTabChange = (value: string) => {
    setActiveTab(value)
    if (value === 'invites') {
      fetchInvites() // 切换到邀请标签时刷新邀请列表
    }
  }

  // 渲染加载状态
  if (isLoading) {
    return (
      <div className="space-y-6">
        <Card>
          <CardHeader>
            <Skeleton className="h-5 w-32" />
            <Skeleton className="h-4 w-48" />
          </CardHeader>
          <CardContent>
            <Skeleton className="h-10 w-full mb-4" />
            <div className="space-y-3">
              <Skeleton className="h-12 w-full" />
              <Skeleton className="h-12 w-full" />
              <Skeleton className="h-12 w-full" />
            </div>
          </CardContent>
        </Card>
      </div>
    )
  }

  // 渲染错误状态
  if (isError) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>团队管理</CardTitle>
          <CardDescription>管理项目成员和权限</CardDescription>
        </CardHeader>
        <CardContent className="text-center py-10">
          <div className="mb-4">
            <X className="h-12 w-12 text-destructive mx-auto" />
          </div>
          <h3 className="text-lg font-medium">获取团队成员失败</h3>
          <p className="text-muted-foreground mt-2">请检查您的网络连接或刷新页面重试</p>
        </CardContent>
        <CardFooter className="flex justify-center">
          <Button onClick={() => { setIsLoading(true); setIsError(false); fetchMembers(); }}>
            重试
          </Button>
        </CardFooter>
      </Card>
    )
  }

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>团队管理</CardTitle>
              <CardDescription>管理项目成员和权限</CardDescription>
            </div>
            {canManageMembers() && (
              <Button onClick={() => setIsInviteModalOpen(true)}>
                <UserPlus className="mr-2 h-4 w-4" /> 邀请成员
              </Button>
            )}
          </div>
        </CardHeader>
        <CardContent>
          <Tabs defaultValue="members" value={activeTab} onValueChange={handleTabChange}>
            <TabsList className="mb-4">
              <TabsTrigger value="members">成员 ({members.length})</TabsTrigger>
              {canManageMembers() && (
                <TabsTrigger value="invites">邀请 ({invites.length})</TabsTrigger>
              )}
            </TabsList>
            
            <TabsContent value="members">
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-[250px]">成员</TableHead>
                      <TableHead>角色</TableHead>
                      <TableHead className="w-[150px]">加入时间</TableHead>
                      {canManageMembers() && <TableHead className="w-[100px] text-right">操作</TableHead>}
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {members.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={canManageMembers() ? 4 : 3} className="h-24 text-center">
                          暂无成员数据
                        </TableCell>
                      </TableRow>
                    ) : (
                      members.map((member) => (
                        <TableRow key={member.id}>
                          <TableCell>
                            <div className="flex items-center gap-3">
                              <Avatar>
                                <AvatarImage 
                                  src={member.user?.image || ''} 
                                  alt={member.user?.name || '用户'} 
                                />
                                <AvatarFallback>
                                  {member.user?.name ? member.user.name.substring(0, 2).toUpperCase() : 'UN'}
                                </AvatarFallback>
                              </Avatar>
                              <div>
                                <p className="font-medium">{member.user?.name || '未命名用户'}</p>
                                <p className="text-xs text-muted-foreground">{member.user?.email || '无邮箱'}</p>
                              </div>
                            </div>
                          </TableCell>
                          <TableCell>
                            <Badge variant={getRoleBadge(member.role).variant}>
                              {getRoleBadge(member.role).label}
                            </Badge>
                          </TableCell>
                          <TableCell>
                            {new Date(member.joinedAt).toLocaleDateString('zh-CN')}
                          </TableCell>
                          {canManageMembers() && (
                            <TableCell className="text-right">
                              {member.userId !== session?.user?.id && (
                                <DropdownMenu>
                                  <DropdownMenuTrigger asChild>
                                    <Button variant="ghost" size="icon">
                                      <MoreHorizontal className="h-4 w-4" />
                                    </Button>
                                  </DropdownMenuTrigger>
                                  <DropdownMenuContent align="end">
                                    <DropdownMenuLabel>操作</DropdownMenuLabel>
                                    {member.role !== ProjectRole.OWNER && (
                                      <>
                                        <DropdownMenuSeparator />
                                        {((userRole === ProjectRole.OWNER) || 
                                           (userRole === ProjectRole.ADMIN && 
                                            member.role !== ProjectRole.ADMIN)) && (
                                          <>
                                            <DropdownMenuItem
                                              disabled={member.role === ProjectRole.ADMIN}
                                              onClick={() => updateMemberRole(member.id, member.userId, ProjectRole.ADMIN)}
                                            >
                                              设为管理员
                                            </DropdownMenuItem>
                                            <DropdownMenuItem
                                              disabled={member.role === ProjectRole.MEMBER}
                                              onClick={() => updateMemberRole(member.id, member.userId, ProjectRole.MEMBER)}
                                            >
                                              设为成员
                                            </DropdownMenuItem>
                                            <DropdownMenuItem
                                              disabled={member.role === ProjectRole.VIEWER}
                                              onClick={() => updateMemberRole(member.id, member.userId, ProjectRole.VIEWER)}
                                            >
                                              设为观察者
                                            </DropdownMenuItem>
                                            <DropdownMenuSeparator />
                                          </>
                                        )}
                                        {((userRole === ProjectRole.OWNER) || 
                                           (userRole === ProjectRole.ADMIN && 
                                            member.role !== ProjectRole.ADMIN)) && (
                                          <DropdownMenuItem
                                            className="text-destructive"
                                            onClick={() => {
                                              if (confirm(`确认从项目中移除 ${member.user?.name || member.user?.email}？`)) {
                                                removeMember(member.userId)
                                              }
                                            }}
                                          >
                                            <Trash2 className="mr-2 h-4 w-4" />
                                            移除成员
                                          </DropdownMenuItem>
                                        )}
                                      </>
                                    )}
                                  </DropdownMenuContent>
                                </DropdownMenu>
                              )}
                            </TableCell>
                          )}
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </div>
            </TabsContent>

            {canManageMembers() && (
              <TabsContent value="invites">
                <div className="rounded-md border">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="w-[250px]">邮箱</TableHead>
                        <TableHead>角色</TableHead>
                        <TableHead>邀请者</TableHead>
                        <TableHead>过期时间</TableHead>
                        <TableHead className="w-[120px] text-right">操作</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {invites.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={5} className="h-24 text-center">
                            暂无邀请记录
                          </TableCell>
                        </TableRow>
                      ) : (
                        invites.map((invite) => (
                          <TableRow key={invite.id}>
                            <TableCell>{invite.email}</TableCell>
                            <TableCell>
                              <Badge variant={getRoleBadge(invite.role).variant}>
                                {getRoleBadge(invite.role).label}
                              </Badge>
                            </TableCell>
                            <TableCell>
                              <div className="flex items-center gap-2">
                                <Avatar className="h-6 w-6">
                                  <AvatarImage 
                                    src={invite.inviter?.image || ''} 
                                    alt={invite.inviter?.name || '用户'} 
                                  />
                                  <AvatarFallback>
                                    {invite.inviter?.name ? invite.inviter.name.substring(0, 2).toUpperCase() : 'UN'}
                                  </AvatarFallback>
                                </Avatar>
                                <span className="text-sm">{invite.inviter?.name || '未命名用户'}</span>
                              </div>
                            </TableCell>
                            <TableCell>
                              {new Date(invite.expires).toLocaleString('zh-CN')}
                            </TableCell>
                            <TableCell className="text-right">
                              <div className="flex justify-end space-x-1">
                                <Button
                                  variant="ghost"
                                  size="icon"
                                  onClick={() => copyInviteLink(invite.token)}
                                >
                                  {copiedInvite === invite.token ? (
                                    <CheckCircle className="h-4 w-4 text-green-500" />
                                  ) : (
                                    <Copy className="h-4 w-4" />
                                  )}
                                </Button>
                                <Button
                                  variant="ghost"
                                  size="icon"
                                  onClick={() => {
                                    if (confirm(`确认撤销发送给 ${invite.email} 的邀请？`)) {
                                      cancelInvite(invite.id)
                                    }
                                  }}
                                >
                                  <Trash2 className="h-4 w-4 text-destructive" />
                                </Button>
                              </div>
                            </TableCell>
                          </TableRow>
                        ))
                      )}
                    </TableBody>
                  </Table>
                </div>
              </TabsContent>
            )}
          </Tabs>
        </CardContent>
      </Card>

      {/* 邀请对话框 */}
      <Dialog open={isInviteModalOpen} onOpenChange={setIsInviteModalOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>邀请新成员</DialogTitle>
            <DialogDescription>
              向项目中添加新成员，邀请链接将通过邮件发送
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div>
              <label htmlFor="email" className="block text-sm font-medium mb-1">
                邮箱地址
              </label>
              <Input
                id="email"
                type="email"
                placeholder="请输入邮箱地址"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              />
            </div>

            <div>
              <label htmlFor="role" className="block text-sm font-medium mb-1">
                角色
              </label>
              <select
                id="role"
                className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                value={role}
                onChange={(e) => setRole(e.target.value as ProjectRole)}
              >
                {userRole === ProjectRole.OWNER && (
                  <option value={ProjectRole.ADMIN}>管理员</option>
                )}
                <option value={ProjectRole.MEMBER}>成员</option>
                <option value={ProjectRole.VIEWER}>观察者</option>
              </select>
            </div>

            <div>
              <label htmlFor="message" className="block text-sm font-medium mb-1">
                邀请留言 (可选)
              </label>
              <Input
                id="message"
                placeholder="添加邀请留言..."
                value={message}
                onChange={(e) => setMessage(e.target.value)}
              />
            </div>
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsInviteModalOpen(false)}
            >
              取消
            </Button>
            <Button onClick={sendInvite} disabled={!email || isSending}>
              {isSending ? "发送中..." : "发送邀请"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
} 
